import collections
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        node = root
        stack = collections.deque([node])
        while stack:
            node = stack.popleft()
            left_node = node.left
            node.left = node.right
            node.right = left_node
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return root

